package cn.iocoder.yudao.module.design.controller.admin.wallet;

import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.design.controller.admin.wallet.vo.recharge.DesignPayWalletRechargeCreateReqVO;
import cn.iocoder.yudao.module.design.controller.admin.wallet.vo.recharge.DesignPayWalletRechargeCreateRespVO;
import cn.iocoder.yudao.module.design.convert.wallet.DesignPayWalletRechargeConvert;
import cn.iocoder.yudao.module.pay.api.notify.dto.PayOrderNotifyReqDTO;
import cn.iocoder.yudao.module.pay.controller.admin.order.vo.PayOrderSubmitReqVO;
import cn.iocoder.yudao.module.pay.controller.admin.order.vo.PayOrderSubmitRespVO;
import cn.iocoder.yudao.module.pay.controller.app.wallet.vo.recharge.AppPayWalletRechargeCreateReqVO;
import cn.iocoder.yudao.module.pay.controller.app.wallet.vo.wallet.AppPayWalletRespVO;
import cn.iocoder.yudao.module.pay.convert.wallet.PayWalletConvert;
import cn.iocoder.yudao.module.pay.dal.dataobject.order.PayOrderDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletRechargeDO;
import cn.iocoder.yudao.module.pay.framework.pay.core.WalletPayClient;
import cn.iocoder.yudao.module.pay.service.order.PayOrderService;
import cn.iocoder.yudao.module.pay.service.wallet.PayWalletRechargeService;
import cn.iocoder.yudao.module.pay.service.wallet.PayWalletService;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserType;

/**
 * @author jason
 */
@Tag(name = "设计师 APP - 钱包")
@RestController
@RequestMapping("/design/pay/wallet")
@Validated
@Slf4j
public class DesignPayWalletController {

    @Resource
    private PayWalletService payWalletService;

    @Resource
    private PayWalletRechargeService walletRechargeService;


    @Resource
    private PayOrderService orderService;

    @GetMapping("/get")
    @Operation(summary = "获取钱包")
    @PreAuthenticated
    public CommonResult<AppPayWalletRespVO> getPayWallet() {
        PayWalletDO wallet = payWalletService.getOrCreateWallet(getLoginUserId(), 3);
        return success(PayWalletConvert.INSTANCE.convert(wallet));
    }

    @PostMapping("/wallet-recharge/create")
    @Operation(summary = "创建钱包充值记录（发起充值）")
    public CommonResult<DesignPayWalletRechargeCreateRespVO> createWalletRecharge(
            @Valid @RequestBody DesignPayWalletRechargeCreateReqVO requestVO) {
        // 前端传入输入1实际支付金额是0.01 所以要扩大100倍
        requestVO.setPayPrice( requestVO.getPayPrice()*100);
        AppPayWalletRechargeCreateReqVO appReqVO = DesignPayWalletRechargeConvert.INSTANCE.convert(requestVO );
        PayWalletRechargeDO walletRecharge = walletRechargeService.createWalletRecharge( WebFrameworkUtils.getLoginUserId(),
               3, getLoginUserId().toString(),  appReqVO);
        // 产生充值记录订单
        //  获取订单详情
        PayOrderDO order = orderService.getOrder( walletRecharge.getPayOrderId());
        // 发起支付
        // 1. 钱包支付事，需要额外传 user_id 和 user_type
        PayOrderSubmitReqVO reqVO = new PayOrderSubmitReqVO();
        Map<String, String> channelExtras = reqVO.getChannelExtras() == null ?
                Maps.newHashMapWithExpectedSize(2) : reqVO.getChannelExtras();
        channelExtras.put(WalletPayClient.USER_ID_KEY, String.valueOf(WebFrameworkUtils.getLoginUserId()));
        channelExtras.put(WalletPayClient.USER_TYPE_KEY, String.valueOf(getLoginUserType()));
        channelExtras.put("openid",requestVO.getOpenId());
        reqVO.setChannelExtras(channelExtras);
        reqVO.setId(order.getId());
        // 目前写死 微信小程序支付
        reqVO.setChannelCode(PayChannelEnum.WX_LITE.getCode());
        reqVO.setReturnUrl("https://"+getClientIP()+":9001/pay/cashier?id=" + order.getId() + "&returnUrl=/design/pay/wallet?id=" + walletRecharge.getId()+"&payOrderId="+walletRecharge.getPayOrderId());
        // 2. 提交支付
        PayOrderSubmitRespVO respVO = orderService.submitOrder(reqVO, getClientIP());
        log.info("微信小程序支付  respVO",respVO);
        DesignPayWalletRechargeCreateRespVO convert = DesignPayWalletRechargeConvert.INSTANCE.convert(respVO);
        convert.setId(walletRecharge.getId());
        convert.setPayOrderId(walletRecharge.getPayOrderId());
        return success(convert);
    }
    @PostMapping("/update-paid")
    @Operation(summary = "更新钱包充值为已充值") // 由 pay-module 支付服务，进行回调，可见 PayNotifyJob
    @PermitAll // 无需登录， 内部校验实现

    public CommonResult<Boolean> updateWalletRechargerPaid(@Valid @RequestBody PayOrderNotifyReqDTO notifyReqDTO) {
        walletRechargeService.updateWalletRechargerPaid(Long.valueOf(notifyReqDTO.getMerchantOrderId()),
                notifyReqDTO.getPayOrderId());
        return success(true);
    }

}
